/*
 * @Author: master
 * @Date: 2022-04-07 17:59:27
 * @LastEditTime: 2024-03-05 12:48:11
 * @Description: cesium 插件钩子
 */
import serveStatic from 'serve-static'; // 静态服务
const path = require('path'); // 路径服务
const fs = require('fs-extra');
export default () => {
  const sourcePath = 'main/components/index.js';
  let baseUrl = 'hubPath/index.js';
  let isBuild = false; // 开发或打包模式
  let outDir = 'dist'; // 输出目录
  return {
    name: 'vite-copy-static-server',
    // vite的配置
    config(config, { command }) {
      isBuild = command !== 'serve';
      // 配置输出目录
      if (config.build?.outDir) {
        outDir = config.build.outDir;
      }
      baseUrl = path.join(config.base, baseUrl);
      // config.define.viteConfig.CESIUM_BASE_URL = CESIUM_BASE_URL;
      return config;
    },
    // 开发服务器的钩子
    configureServer({ middlewares }) {
      const cesiumPath = path.join(__dirname, '../..', sourcePath);
      middlewares.use(path.join('/', baseUrl), serveStatic(cesiumPath));
    },
    // 关闭服务
    async closeBundle() {
      if (isBuild) {
        try {
          await fs.copy(path.join(__dirname, sourcePath), path.join(outDir, sourcePath));
        } catch (err) {
          console.error('copy failed', err);
        }
      }
    },
  };
};
